package com.mlz.mlzmall.ui.activity.frag.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.CartInfo;

import com.mlz.mlzmall.custom.WheelView;
import com.mlz.mlzmall.ui.activity.act.order.ConfirmOrderActivity;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.LoginActivity;
import com.mlz.mlzmall.ui.activity.frag.base.BaseFragment;
import com.mlz.mlzmall.ui.adapter.ShoppingCartAdapter;
import com.mlz.mlzmall.ui.dialog.CartWheelDialog;
import com.mlz.mlzmall.ui.inter.NetResponses;
import com.mlz.mlzmall.ui.model.StringTools;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.util.CacheUtils;
import com.mlz.mlzmall.ui.utils.util.ListViewUtils;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import com.mlz.mlzmall.volley.util.JsonUtils;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class ShoppingCartFragment extends BaseFragment implements NetResponses, View.OnClickListener {
    // 加载数据的类型
    int DataType;
    ListView aListView, bListView;
    int resource;
    RelativeLayout view;
    TextView countCart;
    ImageView over1000;

    ArrayList<CartInfo.CartProductDto> NSCdatalist, SELFdatalist;

    CartInfo.CartTotalDto totals = null;
    ArrayList<CartInfo.CartProductDto> products = new ArrayList<CartInfo.CartProductDto>();


    RelativeLayout rl_back;
    CheckBox cb_trunk_selete;  // 仓库的选择
    CheckBox cb_trunk_selete1;  // 仓库的选择
    LinearLayout trunkTitleLinerLayout, trunkTitleLinerLayout1;
    TextView tv_productTotalMoney;  // 商品的总价
    TextView tv_sellProductCount;   // 卖出商品的总数
    TextView tv_taxTotalMoney;      // 税收的总额
    TextView tv_totalMoney;         // 需要支付总金额
    TextView tv_productTotalMoney1;  // 商品的总价
    TextView tv_sellProductCount1;   // 卖出商品的总数
    TextView tv_totalMoney1;         // 需要支付总金额
    Button bt_Balances;              // 结算按钮
    Button bt_Balances1;
    RelativeLayout taxLinerLayoutB;
    ShoppingCartAdapter addAdapter, addAdapter1;
    ImageView notify, notify_less50;

    int totalProduct = 0;
    int totalProduct1 = 0;
    String  sessionKey, warehouse;


    //数据为空显示的布局
    LinearLayout rl_shopCar_null, rl_out_network;
    ListView[] dataAllList = new ListView[2];
    private String STATUS;
    private int i;
    private String str;
    private Button btOrderChooseRight;


    @Override
    public void onStart() {
        super.onStart();
        sessionKey = ACache.get(getActivity()).getAsString("sessionKeyLogin");
        Log.i("GoogDetailsActivity", "取session成功===" + sessionKey);
        // 获得购物车总数
        getCartquantity();
        // 初始化
        warehouse = "ALL";
        STATUS = "INIT";
        loadData();
        // 接受广播
        receiverBroadcast();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = (RelativeLayout) inflater.inflate(R.layout.shopping_cart_fragment, null);
        setNetResponses(this);
        // 初始化容器
        initView();
        // 弹出式菜单
        popMenu();
        NSCdatalist = new ArrayList<>();
        SELFdatalist = new ArrayList<>();
        dataAllList[0] = aListView;
        dataAllList[1] = bListView;
        // 返回视图
        return view;
    }


    private ScrollView scrollView;
    private Map map = new HashMap();

    // 初始化控件/加载数据
    public void initView() {
        // 如果购物车的数据为空的布局
        rl_shopCar_null = (LinearLayout) view.findViewById(R.id.rl_shopCar_null);
        rl_out_network = (LinearLayout) view.findViewById(R.id.rl_out_network);
        over1000 = (ImageView) view.findViewById(R.id.over1000);
        rl_back = (RelativeLayout) view.findViewById(R.id.iv_back11);
        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onExitFragment != null)
                    onExitFragment.onClick();
            }
        });

        taxLinerLayoutB = (RelativeLayout) view.findViewById(R.id.taxLinerLayoutBalance);
        tv_productTotalMoney = (TextView) view.findViewById(R.id.tv_productTotalMoney);  // 商品的总价
        tv_sellProductCount = (TextView) view.findViewById(R.id.tv_sellProductCount);// 卖出商品的总数
        tv_taxTotalMoney = (TextView) view.findViewById(R.id.tv_taxTotalMoney); // 税收的总额
        tv_totalMoney = (TextView) view.findViewById(R.id.tv_totalMoney);      // 需要支付总金额
        tv_productTotalMoney1 = (TextView) view.findViewById(R.id.tv_productTotalMoney1);  // 商品的总价
        tv_sellProductCount1 = (TextView) view.findViewById(R.id.tv_sellProductCount1);// 卖出商品的总数
        tv_totalMoney1 = (TextView) view.findViewById(R.id.tv_totalMoney1);      // 需要支付总金额
        bt_Balances = (Button) view.findViewById(R.id.bt_Balances);
        bt_Balances1 = (Button) view.findViewById(R.id.bt_Balances1);
        cb_trunk_selete = (CheckBox) view.findViewById(R.id.cb_trunk_selete);
        cb_trunk_selete.setChecked(true);
        cb_trunk_selete.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    StringTools.allselect = 11;
                    StringTools.allSelectNSC = true;
                    map.clear();
                    map.put("warehouse", "NSC");
                    request(Request.Method.POST, URL.CART.SELECT_ALL, map, sessionKey, tag, 100);
                    addAdapter.notifyDataSetChanged();
                } else {
                    StringTools.allselect = 11;
                    StringTools.allSelectNSC = false;
                    map.clear();
                    map.put("warehouse", "NSC");
                    request(Request.Method.POST, URL.CART.UNSELECT_ALL, map, sessionKey, tag, 100);
                    addAdapter.notifyDataSetChanged();
                }
            }
        });
        cb_trunk_selete1 = (CheckBox) view.findViewById(R.id.cb_trunk_selete1);
        cb_trunk_selete1.setChecked(true);
        cb_trunk_selete1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    StringTools.allselect = 12;
                    StringTools.allSelectSELF = true;
                    map.clear();
                    map.put("warehouse", "SELF");
                    request(Request.Method.POST, URL.CART.SELECT_ALL, map, sessionKey, tag, 100);
                    addAdapter1.notifyDataSetChanged();
                } else {
                    StringTools.allselect = 12;
                    StringTools.allSelectSELF = false;
                    map.clear();
                    map.put("warehouse", "SELF");
                    request(Request.Method.POST, URL.CART.UNSELECT_ALL, map, sessionKey, tag, 100);
                    addAdapter1.notifyDataSetChanged();
                }
            }
        });
        trunkTitleLinerLayout = (LinearLayout) view.findViewById(R.id.trunkTitleLinerLayout);
        trunkTitleLinerLayout1 = (LinearLayout) view.findViewById(R.id.trunkTitleLinerLayout1);


        aListView = (ListView) view.findViewById(R.id.cart_shopping_listview);
        bListView = (ListView) view.findViewById(R.id.cart_shopping_listview1);
        resource = R.layout.shopping_cart_item;
        countCart = (TextView) view.findViewById(R.id.countCart);
        scrollView = (ScrollView) view.findViewById(R.id.scrollView_11);

        // 结算按钮
        bt_Balances.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isLogin = CacheUtils.getBoolean(getActivity(), "Logined", false);
                if (!isLogin) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    if (totalProduct > 0) {
                        Intent intent = new Intent(getActivity(), ConfirmOrderActivity.class);
                        intent.putExtra("warehouse", "NSC");
                        getActivity().startActivity(intent);
                        StringTools.shoppingGoBack = 400;
                        StringTools.ffff = 100;
                    } else {
                        Toast.makeText(getActivity(), "您没有选中任何商品", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        bt_Balances1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isLogin = CacheUtils.getBoolean(getActivity(), "Logined", false);
                if (!isLogin) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    if (totalProduct1 > 0) {
                        Intent intent = new Intent(getActivity(), ConfirmOrderActivity.class);
                        intent.putExtra("warehouse", "SELF");
                        getActivity().startActivity(intent);
                        StringTools.shoppingGoBack = 400;
                    } else {
                        Toast.makeText(getActivity(), "您没有选中任何商品", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    public void loadData() {
        request(Request.Method.GET, URL.CART.LIST, null, sessionKey, "ShoppingCart", 30);
    }

    // 弹出式菜单
    public void popMenu() {
        btOrderChooseRight = (Button) view.findViewById(R.id.btOrderChooseRight);
        btOrderChooseRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
                //     WheelDialog2.show(getActivity());
//                PopupMenu popup = new PopupMenu(view.getContext(), v);
//                popup.getMenu().add(0, 0, 0, "全部订单");
//                popup.getMenu().add(0, 1, 1, "美篮子供应");
//                popup.getMenu().add(0, 2, 2, "海外购");
//                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
//                    public boolean onMenuItemClick(MenuItem item) {
//                        btOrderChooseRight.setText(item.getTitle());
//                        switch (item.getItemId()) {
//                            case 0:
//                                // 全部订单
//                                warehouse = "ALL";
//                                if (products.size()>0) {
//                                    rl_shopCar_null.setVisibility(View.GONE);
//                                    scrollView.setVisibility(View.VISIBLE);
//                                    rl_out_network.setVisibility(View.GONE);
//                                } else {
//                                    rl_shopCar_null.setVisibility(View.VISIBLE);
//                                    scrollView.setVisibility(View.GONE);
//                                    rl_out_network.setVisibility(View.GONE);
//                                }
//                                break;
//                            case 1:
//                                //美篮子供应
//                                warehouse = "SELF";
//                                STATUS = "CHANGE";
//                                if(SELFdatalist.size()>0){
//                                    rl_shopCar_null.setVisibility(View.GONE);
//                                    scrollView.setVisibility(View.VISIBLE);
//                                    trunkTitleLinerLayout.setVisibility(View.GONE);
//                                    trunkTitleLinerLayout1.setVisibility(View.VISIBLE);
//                                }else {
//                                    rl_shopCar_null.setVisibility(View.VISIBLE);
//                                    scrollView.setVisibility(View.GONE);
//                                    rl_out_network.setVisibility(View.GONE);
//                                }
//                                break;
//                            case 2:
//                                //海外购
//                                warehouse = "NSC";
//                                STATUS = "CHANGE";
//                                if(NSCdatalist.size()>0){
//                                    rl_shopCar_null.setVisibility(View.GONE);
//                                    scrollView.setVisibility(View.VISIBLE);
//                                    trunkTitleLinerLayout1.setVisibility(View.GONE);
//                                    trunkTitleLinerLayout.setVisibility(View.VISIBLE);
//                                }else {
//                                    rl_shopCar_null.setVisibility(View.VISIBLE);
//                                    scrollView.setVisibility(View.GONE);
//                                    rl_out_network.setVisibility(View.GONE);
//                                }
//                                break;
//                        }
//                        return true;
//                    }
//                });
//                popup.show();
            }
        });
    }

    public static View pw;
    public static PopupWindow pWindow;
    private static WheelView wheelView;
    private static String[] mProvinceDatas = {"","","所有仓库", "美篮子供应", "海外购"};
    private static RelativeLayout rl;
    private static Button btn_confirm;
    private Button btn_cancel;

    private void showDialog() {
        pw = LayoutInflater.from(getActivity()).inflate(R.layout.cart_wheel_layout, null);
        wheelView = (WheelView) pw.findViewById(R.id.wheelView);
        btn_confirm = (Button) pw.findViewById(R.id.btn_confirm);
        btn_cancel = (Button) pw.findViewById(R.id.btn_cancel);
        wheelView.setBackgroundResource(R.color.colorWhite);
        for (int i = 0; i < mProvinceDatas.length; i++) {
            wheelView.addData(mProvinceDatas[i]);
        }
        wheelView.setCenterItem(3);
        pWindow = new PopupWindow(pw, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);//弹框显示大小
        pWindow.setFocusable(true);
        pWindow.setOutsideTouchable(true);
        pWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));//设置背景为透明
        pWindow.setAnimationStyle(R.style.AnimationCenter);
        pWindow.showAtLocation(pw, Gravity.BOTTOM, 0, 0);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData(i);
                btOrderChooseRight.setText(wheelView.getCenterItem().toString());
                pWindow.dismiss();
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pWindow.dismiss();
            }
        });

    }

    private void getData(int i) {
        switch (i) {
            case 0:
                // 全部订单
                warehouse = "ALL";
                if (products.size() > 0) {
                    rl_shopCar_null.setVisibility(View.GONE);
                    scrollView.setVisibility(View.VISIBLE);
                    rl_out_network.setVisibility(View.GONE);
                } else {
                    rl_shopCar_null.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.GONE);
                    rl_out_network.setVisibility(View.GONE);
                }
                break;
            case 1:
                //美篮子供应
                warehouse = "SELF";
                STATUS = "CHANGE";
                if (SELFdatalist.size() > 0) {
                    rl_shopCar_null.setVisibility(View.GONE);
                    scrollView.setVisibility(View.VISIBLE);
                    trunkTitleLinerLayout.setVisibility(View.GONE);
                    trunkTitleLinerLayout1.setVisibility(View.VISIBLE);
                } else {
                    rl_shopCar_null.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.GONE);
                    rl_out_network.setVisibility(View.GONE);
                }
                break;
            case 2:
                //海外购
                warehouse = "NSC";
                STATUS = "CHANGE";
                if (NSCdatalist.size() > 0) {
                    rl_shopCar_null.setVisibility(View.GONE);
                    scrollView.setVisibility(View.VISIBLE);
                    trunkTitleLinerLayout1.setVisibility(View.GONE);
                    trunkTitleLinerLayout.setVisibility(View.VISIBLE);
                } else {
                    rl_shopCar_null.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.GONE);
                    rl_out_network.setVisibility(View.GONE);
                }
                break;
        }

    }

    // 接受广播
    private void receiverBroadcast() {
        IntentFilter filter = new IntentFilter(ShoppingCartAdapter.action);
        filter.addAction("OUTLOGIN");
        getActivity().registerReceiver(broadcastReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(broadcastReceiver);
    }

    // 新建广播接收器
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("OUTLOGIN")) {
                countCart.setText("0");
            } else {
                countCart.setText(StringTools.CartQulity + "");
            }
        }
    };

    //获取购物车总数
    public void getCartquantity() {
        System.out.println("=======@@@");
        request(Request.Method.GET, URL.CART.TOTAL_QTY, null, sessionKey, "ShoppingCart", 20);
    }


    @Override
    public void success(int type, JSONObject jsonObject) {
        JSONObject object = jsonObject.optJSONObject("data");
        switch (type) {
            case 20:
                String count = object.optString("quantity");
                System.out.println("count===" + count);
                countCart.setText(count);
                onExitFragment.setCartTotal(count);
                break;
            case 100:
                STATUS = "CHANGE";
                getCartquantity();
                loadData();
                break;
            case 104:
                STATUS = "CHANGE";
                getCartquantity();
                loadData();
                break;
            case 30:
                CartInfo cartInfo = JsonUtils.object(jsonObject.toString(), CartInfo.class);
                System.out.println("@#$$==="+cartInfo.getData());
                if (!cartInfo.getData().isEmpty()) {
                    System.out.println("@#$$===hand");
                    rl_shopCar_null.setVisibility(View.GONE);
                    scrollView.setVisibility(View.VISIBLE);
                    rl_out_network.setVisibility(View.GONE);
                } else {
                    rl_shopCar_null.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.GONE);
                    rl_out_network.setVisibility(View.GONE);
                    break;
                }
                NSCdatalist.clear();
                SELFdatalist.clear();
                products.clear();
                for (int i = 0; i < cartInfo.getData().size(); i++) {
                    // 取到单个商品放在集合里
                    List<CartInfo.CartProductDto> productsList = cartInfo.getData().get(i).getProducts();
                    totals = cartInfo.getData().get(i).getTotals();
                    Iterator<CartInfo.CartProductDto> it = productsList.iterator();
                    while (it.hasNext()) {
                        CartInfo.CartProductDto cartInfoDataProduct = it.next();
                        if ("NSC".equals(cartInfoDataProduct.getWarehouse())) {
                            NSCdatalist.add(cartInfoDataProduct);
                            products.add(cartInfoDataProduct);
                        } else if ("SELF".equals(cartInfoDataProduct.getWarehouse())) {
                            SELFdatalist.add(cartInfoDataProduct);
                            products.add(cartInfoDataProduct);
                        }
                    }
                }

                if ("INIT".equals(STATUS) && products.size() > 0) {
                    addAdapter = new ShoppingCartAdapter(this, resource, NSCdatalist, StringTools.allSelectNSC);
                    addAdapter1 = new ShoppingCartAdapter(this, resource, SELFdatalist, StringTools.allSelectSELF);
                }
                if (products.size() > 0) {
                    if (NSCdatalist.size() > 0) {
                        trunkTitleLinerLayout.setVisibility(View.VISIBLE);
                        aListView.setAdapter(addAdapter);
                        addAdapter.notifyDataSetChanged();
                        ListViewUtils.setListViewHeightBasedOnChildren(aListView, false);
                    } else if ("SELF".equals(warehouse) && SELFdatalist.size() > 0) {
                        trunkTitleLinerLayout1.setVisibility(View.VISIBLE);
                        bListView.setAdapter(addAdapter1);
                        addAdapter1.notifyDataSetChanged();
                        ListViewUtils.setListViewHeightBasedOnChildren(bListView, false);
                    }
                    totalProduct = 0;
                    if (totals != null) {
                        for (int i = 0; i < products.size(); i++) {
                            if (products.get(i).isSelected()) {
                                totalProduct += products.get(i).getQuantity();
                            }
                        }
                        DecimalFormat df = new DecimalFormat("0.00 ");
                        tv_sellProductCount.setText(totalProduct + "");
                        tv_productTotalMoney.setText("￥" + df.format(totals.getSub_total().getValue()));
                        tv_totalMoney.setText("￥" + df.format(totals.getTotal().getValue()));
                        tv_taxTotalMoney.setText("￥" + df.format(totals.getTax().getValue()));
                        if (totals.total.getValue() > 1000) {
                            over1000.setVisibility(View.VISIBLE);
                            bt_Balances.setEnabled(false);
                            bt_Balances.setBackgroundColor(getResources().getColor(R.color.text_seleted));
                        } else {
                            over1000.setVisibility(View.GONE);
                            bt_Balances.setEnabled(true);
                            bt_Balances.setBackgroundColor(getResources().getColor(R.color.text_unseleted));
                        }
                    }
                } else {
                    rl_shopCar_null.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.GONE);
                    rl_out_network.setVisibility(View.GONE);
                }
                if (SELFdatalist.isEmpty()) {
                    trunkTitleLinerLayout1.setVisibility(View.GONE);
                }

                break;
        }
    }

    @Override
    public void fail() {
        System.out.println("======请求失败");
        countCart.setText("0");
        onExitFragment.setCartTotal("0");
        rl_shopCar_null.setVisibility(View.GONE);
        scrollView.setVisibility(View.GONE);
        rl_out_network.setVisibility(View.VISIBLE);
    }

    public interface OnExitFragment {
        void onClick();

        void setCartTotal(String cartquan);
    }

    private OnExitFragment onExitFragment;

    public void setOnExitFragment(OnExitFragment onExitFragment) {
        this.onExitFragment = onExitFragment;
    }


}
